package com.itjiange.springbootinit.mq;

import com.rabbitmq.client.*;

/**
 * @author ITjiange
 */
public class TopicConsumer {

    private static final String EXCHANGE_NAME = "topic-exchange";
    private static final String QUEUE_FRONT = "qian";
    private static final String QUEUE_BACKEND = "hou";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("154.8.205.195");
        factory.setUsername("itjiange");
        factory.setPassword("123456");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);

        // 前端任务队列
        channel.queueDeclare(QUEUE_FRONT, false, false, false, null);
        channel.queueBind(QUEUE_FRONT, EXCHANGE_NAME, "#.前端.#");

        // 后端任务队列
        channel.queueDeclare(QUEUE_BACKEND, false, false, false, null);
        channel.queueBind(QUEUE_BACKEND, EXCHANGE_NAME, "#.后端.#");

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback1 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [前端] Received '" +
                    delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        channel.basicConsume(QUEUE_FRONT, true, deliverCallback1, consumerTag -> {
        });

        DeliverCallback deliverCallback2 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [后端] Received '" +
                    delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        channel.basicConsume(QUEUE_BACKEND, true, deliverCallback2, consumerTag -> {
        });
    }
}